package com.tanhua.server.service;


import com.aliyuncs.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.autoconfig.template.SmsTemplate;


import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.dubbo.api.SettingsApi;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.dubbo.api.UserLikeApi;
import com.tanhua.model.domain.User;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import io.jsonwebtoken.Jwts;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;


import java.time.Duration;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {

    @Autowired
    private SmsTemplate smsTemplate;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @DubboReference
    private UserApi userApi;
    @DubboReference
    private SettingsApi settingsApi;
    @Autowired
    private HuanXinTemplate huanXinTemplate;
    @DubboReference
    private UserLikeApi userLikeApi;
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private MqMessageService mqMessageService;
    @Autowired
    private UserFreezeService userFreezeService;

    /**
     * 发送验证码
     *
     * @param phone
     */
    public void sendMsg(String phone) {
        User user = userApi.findByMobile(phone);
        if (user!=null){
            userFreezeService.checkUserStatus("1",user.getId());
        }
        //生成6位验证码
//        String code = RandomStringUtils.randomNumeric(6);
        String code = "999999";     //自定义验证码
        //调用SmsTemplate发送验证码到手机
//        smsTemplate.sendSms(phone, code);
        //将验证码存入到Redis 设置验证码有效时间为5分钟：Duration.ofMinutes(5)
        redisTemplate.opsForValue().set("CHECK_CODE" + phone, code, Duration.ofMinutes(5));
    }

    /**
     * 校验验证码
     *
     * @param phone
     * @param code
     */
    public Map loginVerification(String phone, String code) {
        //获取验证码
        String redisCode = redisTemplate.opsForValue().get("CHECK_CODE" + phone);
        //校验验证码（验证码是否存在，是否与输入的验证码一致）
        if (StringUtils.isEmpty(redisCode) || !redisCode.equals(code)) {
            throw new BusinessException(ErrorResult.loginError());
        }
        //删除验证码
        redisTemplate.delete(redisCode);
        //通过手机号查询用户
        User user = userApi.findByMobile(phone);

        boolean isNew = false;
        //判断用户是否存在，如果不存在保存到数据库中
        if (user == null) {
            user = new User();
            user.setMobile(phone);
            user.setPassword(DigestUtils.md5Hex("123456"));
            Long userId = userApi.save(user);
            user.setId(userId);
            isNew = true;
            //如果用户添加成功，就继续注册环信账号
            String hxUser = "hx" + user.getId();
            Boolean aBoolean = huanXinTemplate.createUser(hxUser, Constants.INIT_PASSWORD);
            if (aBoolean) {
                user.setHxUser(hxUser);
                user.setHxPassword(Constants.INIT_PASSWORD);
                userApi.update(user);
            }
        }
        //生成日志登录
        mqMessageService.sendLogMessage(user.getId(), "0101", "user", null);
        //通过Jwt生成token
        Map tokenMap = new HashMap<>();
        tokenMap.put("id", user.getId());
        tokenMap.put("mobile", phone);
        String token = JwtUtils.getToken(tokenMap);
        //构造返回值
        Map retMap = new HashMap();
        retMap.put("token", token);
        retMap.put("isNew", isNew);
        return retMap;
    }

    /**
     * 校验验证码
     *
     * @param mobile
     * @param verificationCode
     */
    public boolean checkVerificationCode(String mobile, String verificationCode) {
        System.err.println(verificationCode);
        //获取验证码
        String redisCode = redisTemplate.opsForValue().get("CHECK_CODE" + mobile);
        //校验验证码（验证码是否存在，是否与输入的验证码一致）
        if (StringUtils.isEmpty(redisCode) || !redisCode.equals(verificationCode)) {
            throw new BusinessException(ErrorResult.loginError());
        }
        //删除验证码
        redisTemplate.delete(redisCode);
        //验证码正确，返回true
        return true;
    }

    /**
     * 更换手机号
     *
     * @param phone
     */
    public void updatePhone(String phone) {
        //查询当前输入的手机号是否存在数据库中
        Boolean flag = settingsApi.getPhone(phone);
        if (!flag) {
            throw new BusinessException(ErrorResult.mobileError());
        } else {
            //获取用户id
            Long userId = UserHolder.getUserId();
            settingsApi.updatePhone(userId, phone);
        }
    }

    public void getPhone(String phone) {
        Long id = UserHolder.getUserId();
        //校验验证码是否为重复
        boolean result = settingsApi.getPhone(phone);
        if (!result) {
            throw new BusinessException(ErrorResult.mobileError());
        }
        //检查数据库中是否有相同的方法
        User user = userApi.findById(id);
        user.setMobile(phone);
        System.out.println(user.getId());
        userApi.updatePhone(user);
    }

    /**
     * 互相喜欢，喜欢，粉丝 - 统计
     *
     * @return
     */
    public Map counts() {
        //获取当前用户
        Map map = userLikeApi.findById(UserHolder.getUserId());
        return map;
    }
}
